'''
Created on 30/03/2014

@author: juampi
'''
import tablature
from chordinstrument import Position

class Parser(object):
    '''
    classdocs
    '''


    def __init__(self,source):
        '''
        Constructor
        '''
        self.source = source
        
    def find_offsets(self,line,string_number):
        
        digits_and_offsets = []
        for x in range(len(line)):
            if line[x].isdigit():
                digits_and_offsets.append([line[x],x])
                
        FRET,OFFSET = range(2)
        x = 0
                        
        while x < len(digits_and_offsets):                            
            if digits_and_offsets[x] == digits_and_offsets[-1]:
                break
            elif digits_and_offsets[x] is None:
                continue
            else:
                if digits_and_offsets[x][OFFSET] == digits_and_offsets[x + 1][OFFSET] -1:
                    digits_and_offsets[x][FRET] = '%s%s' % (digits_and_offsets[x][FRET],digits_and_offsets[x + 1][FRET])
                    try:                        
                        digits_and_offsets[x + 1] = None
                    except IndexError:
                        break                
                    x += 2
                else:
                    x += 1
                    
        digits_and_offsets = filter(lambda x: x is not None,digits_and_offsets)
        result = []
        for x in digits_and_offsets:
            result.append(tablature.Chords(x[OFFSET],Position(string_number,int(x[FRET]))))
            
        return result
        #fret = x
        #tablature.Chords(offset=x,position=(chord_number,fret))
    
    def resolve(self):
        strip_chord = lambda line: line[line.index('|') + 1: line.rindex('|')]        
        lines = self.source.split('\n')
        
        filter_lines = []
        for line in lines:
            line = line.strip()
            if line:
                l = strip_chord(line)
                filter_lines.append(l)
        
        chords = []
        for x in range(len(filter_lines)):
            chords += self.find_offsets(filter_lines[x],x)
        return chords
            
                
                
        
        
                
                
            
        
        
        
            
        